package secure

import (
	"strings"

	"github.com/gin-contrib/secure"
	"github.com/gin-gonic/gin"

	"github.com/super-team/start-kit/configs"
)

func Secure() gin.HandlerFunc {
	cfg := configs.Config.Secure
	c := secure.Config{
		STSSeconds:              cfg.STSSeconds,
		STSIncludeSubdomains:    cfg.STSIncludeSubdomains,
		FrameDeny:               cfg.FrameDeny,
		ContentTypeNosniff:      cfg.ContentTypeNosniff,
		BrowserXssFilter:        cfg.BrowserXssFilter,
		IsDevelopment:           configs.Config.Server.Debug,
		IENoOpen:                cfg.IENoOpen,
		CustomFrameOptionsValue: cfg.CustomFrameOptionsValue,
		SSLRedirect:             cfg.SSLRedirect,
		ContentSecurityPolicy:   cfg.ContentSecurityPolicy,
		ReferrerPolicy:          cfg.ReferrerPolicy,
	}
	if cfg.SSLProxyHeaders != "" {
		proxyData := strings.Split(cfg.SSLProxyHeaders, ",")
		if len(proxyData) > 0 {
			d := map[string]string{}
			for _, datum := range proxyData {
				dd := strings.Split(datum, ":")
				if len(dd) == 2 {
					d[dd[0]] = dd[1]
				}
			}
			if len(d) > 0 {
				c.SSLProxyHeaders = d
			}
		}
	}
	if cfg.AllowHosts != "*" {
		c.AllowedHosts = strings.Split(cfg.AllowHosts, ",")
	}
	return secure.New(c)
}
